package com.itheima.reggie.controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    @CacheEvict(value = "dish_",key = "#dishDto.categoryId")
    public R add(@RequestBody DishDto dishDto){
        dishService.addWithFlavor(dishDto);
//        String key = "dish_"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);
        return R.success("添加成功");
    }


    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){
        IPage<Dish> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)){
            lqw.like(Dish::getName,name);
        }
        lqw.orderByDesc(Dish::getUpdateTime);
        IPage<Dish> ipage = dishService.page(pageInfo, lqw);
        IPage<DishDto> dishDtoIPage = new Page<>();
        BeanUtils.copyProperties(ipage,dishDtoIPage,"records");
        List<Dish> records = ipage.getRecords();
        List<DishDto> list =  records.stream().map(record->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoIPage.setRecords(list);
        return R.success(dishDtoIPage);
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value = "dish_",key = "#dishDto.categoryId")
    public R update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
//        String key = "dish_"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "dish_",key = "#dish.categoryId")
    public R list(Dish dish){
        List<DishDto> dishDtolist = null;
//        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();
//        dishDtolist = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        if (dishDtolist!=null&&dishDtolist.size()>0){
//            return R.success(dishDtolist);
//        }
        LambdaQueryWrapper<Dish> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lqw1.eq(Dish::getStatus,1);
        lqw1.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw1);
        dishDtolist =  list.stream().map(record->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            Long dishId = record.getId();
            LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lqw2);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
//        redisTemplate.opsForValue().set(key,dishDtolist,60, TimeUnit.MINUTES);
        return R.success(dishDtolist);
    }


    @PostMapping("/status/{status}")
    public R updateStatus( @RequestParam List<Long> ids,@PathVariable Integer status){
        dishService.updateByIds(ids,status);
        return R.success(status);
    }


    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }
}
